#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QGroupBox>
#include <QRadioButton>
#include <QDial>
#include <qDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("Paint");
    setWindowIcon(style()->standardIcon(QStyle::SP_DialogResetButton));

    scene = new GraphicsScene(this);
    scene->setSceneRect(0, 0, ui->graphicsView->width() - 20,
                        ui->graphicsView->height() - 20);

    connect(scene, &GraphicsScene::signalActionMode, this, &MainWindow::slotActionMode);
    connect(scene, &GraphicsScene::signalShiftPress, this, &MainWindow::slotShiftPress);
    connect(scene, &GraphicsScene::signalShiftRelease, this, &MainWindow::slotShiftRelease);

    ui->graphicsView->setRenderHint(QPainter::Antialiasing);
    ui->graphicsView->setScene(scene);
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    createToolBar();
    createDockWidget_selectFigure();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::createToolBar()
{
    ui->mainToolBar->addAction(style()->standardIcon(QStyle::SP_DialogSaveButton),
                               "Сохранить картинку",
                               this,
                               &slotSave);
    ui->mainToolBar->addAction(style()->standardIcon(QStyle::SP_DialogOpenButton),
                               "Загрузить картинку",
                               this,
                               &slotOpen);
    ui->mainToolBar->addSeparator();
    ui->mainToolBar->addAction(style()->standardIcon(QStyle::SP_DialogResetButton),
                               "Режим рисования",
                               this,
                               &slotDrawMode);
    ui->mainToolBar->addAction(style()->standardIcon(QStyle::SP_ToolBarVerticalExtensionButton),
                               "Режим выделения",
                               this,
                               &slotSelectMode);
    ui->mainToolBar->addSeparator();
    ui->mainToolBar->addAction(style()->standardIcon(QStyle::SP_DialogCancelButton),
                               "Отчистить картинку",
                               this,
                               &slotClear);

}

void MainWindow::createDockWidget_selectFigure()
{
    dockWidget_selectFigure = new QDockWidget("Режим рисования");
    QGroupBox* groupBox = new QGroupBox();
    QLayout* layout = new QVBoxLayout();

    QRadioButton* radioButton1 = new QRadioButton("Прямоугольник");
    layout->addWidget(radioButton1);

    QRadioButton* radioButton2 = new QRadioButton("Круг");
    layout->addWidget(radioButton2);
    radioButton2->setChecked(true);
    scene->slotCircleMode();

    QRadioButton* radioButton3 = new QRadioButton("Треугольник");
    layout->addWidget(radioButton3);

    groupBox->setLayout(layout);
    dockWidget_selectFigure->setWidget(groupBox);
    addDockWidget(Qt::LeftDockWidgetArea, dockWidget_selectFigure);
    dockWidget_selectFigure->setFloating(true);
    dockWidget_selectFigure->setFeatures(QDockWidget::DockWidgetMovable
                                         | QDockWidget::DockWidgetFloatable);
    dockWidget_selectFigure->setMaximumSize(QSize(120,80));


    connect(radioButton1, &QRadioButton::clicked, scene, &GraphicsScene::slotRectangleMode);
    connect(radioButton2, &QRadioButton::clicked, scene, &GraphicsScene::slotCircleMode);
    connect(radioButton3, &QRadioButton::clicked, scene, &GraphicsScene::slotTriangleMode);
    dockWidget_selectFigure->move(this->rect().center() - QPoint(-12, 362));
}

void MainWindow::createDockWidget_selectAction()
{
    dockWidget_selectAction = new QDockWidget("Режим преобразований");
    QGroupBox* groupBox = new QGroupBox();
    QLayout* layout = new QVBoxLayout();

    QRadioButton* radioButton1 = new QRadioButton("Сдвиг");
    layout->addWidget(radioButton1);

    QRadioButton* radioButton2 = new QRadioButton("Поворот");
    layout->addWidget(radioButton2);
    radioButton2->setChecked(true);
    slotRotationMode();

    QRadioButton* radioButton3 = new QRadioButton("Растяжение");
    layout->addWidget(radioButton3);

    groupBox->setLayout(layout);
    dockWidget_selectAction->setWidget(groupBox);
    addDockWidget(Qt::LeftDockWidgetArea, dockWidget_selectAction);
    dockWidget_selectAction->setFloating(true);
    dockWidget_selectAction->setFeatures(QDockWidget::DockWidgetMovable
                                         | QDockWidget::DockWidgetFloatable);
    dockWidget_selectAction->setMaximumSize(QSize(150,80));


    connect(radioButton1, &QRadioButton::clicked, this, &MainWindow::slotShiftMode);
    connect(radioButton2, &QRadioButton::clicked, this, &MainWindow::slotRotationMode);
    connect(radioButton3, &QRadioButton::clicked, this, &MainWindow::slotExtensionMode);
    dockWidget_selectAction->move(this->rect().center() - QPoint(17, 362));
}

void MainWindow::slotSave()
{
    statusBar()->showMessage("Сохранение");
    QString fileName = QFileDialog::getSaveFileName(this, tr("Сохранить картинку"), "", tr("Текстовый документ (*.txt)"));
    statusBar()->clearMessage();
    if(scene->writeFile(fileName))
    {
        slotDrawMode();
        statusBar()->showMessage("Картинка успешно сохранена", 1000);
    }
    else
        statusBar()->showMessage("Произошла ошибка сохранения", 1000);
}

void MainWindow::slotOpen()
{
    statusBar()->showMessage("Загрузка");
    QString fileName = QFileDialog::getOpenFileName(this, tr("Загрузить картинку"), "", tr("Текстовый документ (*.txt)"));
    statusBar()->clearMessage();
    if(scene->readFile(fileName))
    {
        slotDrawMode();
        statusBar()->showMessage("Картинка успешно загружена", 1000);
    }
    else
        statusBar()->showMessage("Произошла ошибка загрузки", 1000);
}

void MainWindow::slotDrawMode()
{
    if(!drowModeFlag)
    {
        scene->slotDrowMode();
        if(actionModeFlag)
        {
            dockWidget_selectAction->close();
            delete dockWidget_selectAction;
            if(rotationModeFlag)
            {
                dockWidget_rotationMode->close();
                delete dockWidget_rotationMode;
            }
            if(extensionModeFlag)
            {
                dockWidget_extensionMode->close();
                delete dockWidget_extensionMode;
            }
        }

        drowModeFlag = true;
        selectModeFlag = false;
        actionModeFlag = false;

        ui->graphicsView->setCursor(Qt::ArrowCursor);
        createDockWidget_selectFigure();
    }
    statusBar()->showMessage("Режим рисования", 1000);
}

void MainWindow::slotSelectMode()
{
    scene->slotSelectMode();
    if(!selectModeFlag)
    {
        if(drowModeFlag)
        {
            dockWidget_selectFigure->close();
            delete dockWidget_selectFigure;
        }
        if(actionModeFlag)
        {
            dockWidget_selectAction->close();
            delete dockWidget_selectAction;
            if(rotationModeFlag)
            {
                dockWidget_rotationMode->close();
                delete dockWidget_rotationMode;
            }
            if(extensionModeFlag)
            {
                dockWidget_extensionMode->close();
                delete dockWidget_extensionMode;
            }
        }

        drowModeFlag = false;
        selectModeFlag = true;
        actionModeFlag = false;

        ui->graphicsView->setCursor(Qt::CrossCursor);
    }
    statusBar()->showMessage("Режим выделения", 1000);
}

void MainWindow::slotActionMode(int numSelectedFigures)
{
    drowModeFlag = false;
    selectModeFlag = false;
    actionModeFlag = true;

    createDockWidget_selectAction();
    statusBar()->showMessage("Выбрано фигур: " + QString::number(numSelectedFigures));
}

void MainWindow::slotClear()
{
    if(!drowModeFlag)
    {
        scene->slotDrowMode();
        if(actionModeFlag)
        {
            dockWidget_selectAction->close();
            delete dockWidget_selectAction;
            if(rotationModeFlag)
            {
                dockWidget_rotationMode->close();
                delete dockWidget_rotationMode;
            }
            if(extensionModeFlag)
            {
                dockWidget_extensionMode->close();
                delete dockWidget_extensionMode;
            }
        }

        drowModeFlag = true;
        selectModeFlag = false;
        actionModeFlag = false;

        ui->graphicsView->setCursor(Qt::ArrowCursor);
        createDockWidget_selectFigure();
    }
    scene->clearPicture();
    statusBar()->showMessage("Картинка отчищена", 1000);
}

void MainWindow::slotShiftMode()
{
    if(rotationModeFlag)
    {
        dockWidget_rotationMode->close();
        delete dockWidget_rotationMode;
    }
    if(extensionModeFlag)
    {
        dockWidget_extensionMode->close();
        delete dockWidget_extensionMode;
    }
    shiftModeFlag = true;
    rotationModeFlag = false;
    extensionModeFlag = false;

    ui->graphicsView->setCursor(Qt::OpenHandCursor);
    scene->slotShiftMode();
}

void MainWindow::slotRotationMode()
{    
    if(extensionModeFlag)
    {
        dockWidget_extensionMode->close();
        delete dockWidget_extensionMode;
    }
    shiftModeFlag = false;
    rotationModeFlag = true;
    extensionModeFlag = false;

    ui->graphicsView->setCursor(Qt::ArrowCursor);
    scene->slotRotationMode();

    dockWidget_rotationMode = new QDockWidget("Угол");
    QDial* dial = new QDial;
    dial->setMinimum(0);
    dial->setMaximum(360);
    dial->setSingleStep(1);
    dial->setWrapping(true);
    dial->setNotchesVisible(true);
    dockWidget_rotationMode->setWidget(dial);
    addDockWidget(Qt::LeftDockWidgetArea, dockWidget_rotationMode);
    dockWidget_rotationMode->setFloating(true);
    dockWidget_rotationMode->setFeatures(QDockWidget::DockWidgetMovable
                                         | QDockWidget::DockWidgetFloatable);
    dockWidget_rotationMode->setMaximumSize(QSize(150,150));

    connect(dial, &QDial::valueChanged, scene, &GraphicsScene::slotRotationValue);
    dockWidget_rotationMode->move(this->rect().center() - QPoint(17, 250));
}

void MainWindow::slotExtensionMode()
{
    if(rotationModeFlag)
    {
        dockWidget_rotationMode->close();
        delete dockWidget_rotationMode;
    }
    shiftModeFlag = false;
    rotationModeFlag = false;
    extensionModeFlag = true;
    ui->graphicsView->setCursor(Qt::ArrowCursor);
    scene->slotExtensionMode();

    dockWidget_extensionMode = new QDockWidget("Коэффициент");
    QSlider* slider = new QSlider(Qt::Horizontal);
    slider->setMinimum(0);
    slider->setMaximum(200);
    slider->setValue(100);
    slider->setSingleStep(1);
    dockWidget_extensionMode->setWidget(slider);
    addDockWidget(Qt::LeftDockWidgetArea, dockWidget_extensionMode);
    dockWidget_extensionMode->setFloating(true);
    dockWidget_extensionMode->setFeatures(QDockWidget::DockWidgetMovable
                                         | QDockWidget::DockWidgetFloatable);
    dockWidget_extensionMode->setMinimumSize(QSize(150,40));
    dockWidget_extensionMode->setMaximumSize(QSize(150,40));

    connect(slider, &QDial::valueChanged, scene, &GraphicsScene::slotExtansionValue);
    dockWidget_extensionMode->move(this->rect().center() - QPoint(17, 250));
}

void MainWindow::slotShiftPress()
{
    ui->graphicsView->setCursor(Qt::ClosedHandCursor);
}

void MainWindow::slotShiftRelease()
{
    ui->graphicsView->setCursor(Qt::OpenHandCursor);
}
